from Scripts.mq import conn
from Scripts.headers import config, log_format
from Scripts.mysql import MysqlConn
import logging
import json

from Scripts.mess import send_mess


# 开辟管道
mq = conn(virtual=config.get('mq', 'select_virtual_host'))

# 声明队列，参数为队列名
mq.queue_declare(config.get('mq', 'select_queue'))
logging.basicConfig(level=logging.WARNING, format=log_format)


# 消息处理函数，执行完成才说明接收完成，此时才可以接收下一条，串行
def name_select(v1, v2, v3, body_get):
    logging.warning(f'得到的数据为：{v1}, {v2}, {v3},'
                    f' {json.dumps(json.loads(body_get), indent=4, ensure_ascii=False)}')

    get_value = json.loads(body_get)
    try:
        mess_type = get_value["event"]["chat_type"]
        user_id = get_value["event"]["employee_id"]
        mess_without_at_bot = get_value["event"]["text_without_at_bot"]
        chat_id = get_value["event"]["open_chat_id"]
        # 当所传en_name不为空时开始创建新账号
        if mess_type in ["group"]:
            user_json = {'user_id': user_id,
                         'mess': mess_without_at_bot,
                         'chat_id': chat_id,
                         'id_type': 'chat_id',
                         're_id': chat_id,
                         'en_name': mess_without_at_bot
                         }
        elif mess_type in ["p2p", "private"]:
            user_json = {'user_id': user_id,
                         'mess': mess_without_at_bot,
                         'chat_id': chat_id,
                         'id_type': 'user_id',
                         're_id': user_id,
                         'en_name': mess_without_at_bot
                         }
        else:
            logging.warning('未找到关键字，操作失败。')
            return False
        print(mess_without_at_bot)
        mysql = MysqlConn()
        result = mysql.search_name(mess_without_at_bot)
        if result:
            send_mess(action_type='select_have', user_json_input=user_json)  # 发送消息给相关群
        else:
            send_mess(action_type='select_have_not', user_json_input=user_json)

    except Exception as e:
        logging.warning(f'未找到相关值，操作失败。{e}')


mq.basic_consume(config.get('mq', 'select_queue'), name_select, True)

# 开始接收消息
mq.start_consuming()
